"""
微信视频号直播数据解码器 - 与 wxlivespy 项目逻辑一致
"""
import json
import base64
import time
from app.utils.logger import Logger

class WXDataDecoder:
    """微信直播数据解码器 - 与 wxlivespy 项目逻辑一致"""
    
    @staticmethod
    def decode_data_from_response(request_headers, request_data, response_data):
        """
        从响应中解码数据 - 与 wxlivespy 项目逻辑一致
        
        @param request_headers: 请求头
        @param request_data: 请求数据
        @param response_data: 响应数据
        @return: 解析后的数据，包含主播信息、直播信息和事件列表
        """
        logger = Logger.get_logger("wx_data_decoder")
        
        try:
            # 初始化结果对象
            result = {
                "host_info": {},
                "live_info": {},
                "events": []
            }
            
            # 提取主播信息
            result["host_info"] = {
                "wechat_uin": request_headers.get("x-wechat-uin", ""),
                "finder_username": request_data.get("finderUsername", "")
            }
            
            # 检查 liveInfo 是否存在
            if "data" not in response_data:
                logger.warning("响应数据中没有 data 字段")
                return result
                
            response_data_obj = response_data["data"]
            # 检查 liveInfo 是否为 undefined
            if "liveInfo" not in response_data_obj or response_data_obj["liveInfo"] is None:
                # 检查消息列表是否为空
                msg_list_empty = "msgList" not in response_data_obj or not response_data_obj["msgList"]
                app_msg_list_empty = "appMsgList" not in response_data_obj or not response_data_obj["appMsgList"]
                
                logger.debug(f"消息列表状态: msgList_empty={msg_list_empty}, appMsgList_empty={app_msg_list_empty}")
                
                if msg_list_empty and app_msg_list_empty:
                    logger.warning("响应数据中没有 liveInfo，且消息列表为空")
                    return result
                    
                logger.error("liveInfo 为空，但消息列表不为空")
            
            # 提取直播信息
            if "liveInfo" in response_data_obj and response_data_obj["liveInfo"]:
                result["live_info"] = WXDataDecoder._extract_live_info(response_data_obj["liveInfo"], result["host_info"])
                logger.debug(f"提取到直播信息: {result['live_info']}")
            
            # 提取普通消息事件
            if "msgList" in response_data_obj and response_data_obj["msgList"]:
                logger.debug(f"开始处理 msgList，共 {len(response_data_obj['msgList'])} 条消息")
                for msg in response_data_obj["msgList"]:
                    event = WXDataDecoder._extract_message_from_msg(msg)
                    if event:
                        result["events"].append(event)
                        logger.debug(f"提取到普通消息事件: {event['decoded_type']}")
            
            # 提取应用消息事件（礼物、点赞等）
            if "appMsgList" in response_data_obj and response_data_obj["appMsgList"]:
                logger.debug(f"开始处理 appMsgList，共 {len(response_data_obj['appMsgList'])} 条消息")
                for app_msg in response_data_obj["appMsgList"]:
                    event = WXDataDecoder._extract_message_from_app_msg(app_msg)
                    if event:
                        # 对于 appMsg，需要解码 payload
                        if "payload" in app_msg and app_msg["payload"]:
                            try:
                                decoded_payload = base64.b64decode(app_msg["payload"]).decode('utf-8')
                                gift_payload = json.loads(decoded_payload)
                                # 保存解码后的 payload 到原始数据中
                                app_msg["payload"] = gift_payload
                                logger.debug(f"解码 payload 成功: {gift_payload}")
                            except Exception as e:
                                logger.error(f"解码 payload 失败: {str(e)}")
                        
                        result["events"].append(event)
                        logger.debug(f"提取到应用消息事件: {event['decoded_type']}")
            
            # 记录解码结果
            # if result["events"]:
            #     logger.info(f"解码成功: 获取到 {len(result['events'])} 个事件")
                
            # if result["live_info"]:
            #     logger.info(f"解码成功: 获取到直播信息 {result['live_info'].get('live_id', '')}")
            
            return result
            
        except Exception as e:
            logger.error(f"解码数据失败: {str(e)}")
            import traceback
            logger.error(f"异常堆栈: {traceback.format_exc()}")
            return {"host_info": {}, "live_info": {}, "events": []}
    
    @staticmethod
    def _extract_live_info(live_info_obj, host_info):
        """
        提取直播信息 - 与 wxlivespy 项目逻辑一致
        
        @param live_info_obj: 直播信息对象
        @param host_info: 主播信息
        @return: 提取的直播信息
        """
        # 获取直播状态
        live_status = live_info_obj.get("liveStatus", 0)
        
        live_info = {
            "wechat_uin": host_info.get("wechat_uin", ""),
            "live_id": live_info_obj.get("liveId", ""),
            "live_status": live_status,
            "status": live_status,  # 添加status字段，与live_status保持一致，用于兼容性
            "online_count": live_info_obj.get("onlineCnt", 0),
            "view_count": live_info_obj.get("onlineCnt", 0),  # 添加view_count字段，与online_count保持一致，用于兼容性
            "start_time": live_info_obj.get("startTime", 0),
            "like_count": live_info_obj.get("likeCnt", 0),
            "reward_total_amount_in_wecoin": live_info_obj.get("rewardTotalAmountInWecoin", 0)
        }
        
        return live_info
    
    @staticmethod
    def _extract_message_from_msg(msg):
        """
        从普通消息中提取事件数据 - 与 wxlivespy 项目逻辑一致
        
        @param msg: 消息数据
        @return: 提取的事件数据
        """
        try:
            # 基础事件数据
            event = {
                "msg_time": int(time.time() * 1000),  # 当前时间戳（毫秒）
                "msg_sub_type": msg.get("type", 0),
                "msg_id": msg.get("clientMsgId", ""),
                "sec_openid": msg.get("username", ""),
                "content": msg.get("content", ""),
                "nickname": msg.get("nickname", ""),
                "seq": msg.get("seq", 0)
            }
            
            # 根据消息类型设置解码类型
            if event["msg_sub_type"] == 1:
                event["decoded_type"] = "comment"
            elif event["msg_sub_type"] == 10005:
                event["decoded_type"] = "join"
            else:
                event["decoded_type"] = "unknown"
                event["original_data"] = msg
            
            return event
            
        except Exception as e:
            Logger.get_logger("wx_data_decoder").error(f"提取普通消息事件失败: {str(e)}")
            return None
    
    @staticmethod
    def _extract_message_from_app_msg(app_msg):
        """
        从应用消息中提取事件数据 - 与 wxlivespy 项目逻辑一致
        
        @param app_msg: 应用消息数据
        @return: 提取的事件数据
        """
        try:
            # 基础事件数据
            event = {
                "msg_time": int(time.time() * 1000),  # 当前时间戳（毫秒）
                "msg_sub_type": app_msg.get("msgType", 0),
                "msg_id": app_msg.get("clientMsgId", ""),
                "seq": app_msg.get("seq", 0)
            }
            
            # 提取用户信息
            if "fromUserContact" in app_msg and "contact" in app_msg["fromUserContact"]:
                contact = app_msg["fromUserContact"]["contact"]
                event["sec_openid"] = contact.get("username", "")
                event["nickname"] = contact.get("nickname", "")
            
            # 根据消息类型设置解码类型和额外数据
            if event["msg_sub_type"] == 20009:  # 礼物
                event["decoded_type"] = "gift"
                
                # 解码 payload
                if "payload" in app_msg and app_msg["payload"]:
                    try:
                        decoded_payload = base64.b64decode(app_msg["payload"]).decode('utf-8')
                        gift_payload = json.loads(decoded_payload)
                        
                        event["sec_gift_id"] = gift_payload.get("reward_product_id", "")
                        event["gift_num"] = gift_payload.get("reward_product_count", 0)
                        event["gift_value"] = gift_payload.get("reward_amount_in_wecoin", 0)
                        event["content"] = gift_payload.get("content", "")
                    except Exception as e:
                        Logger.get_logger("wx_data_decoder").error(f"解码礼物 payload 失败: {str(e)}")
                
            elif event["msg_sub_type"] == 20013:  # 连击礼物
                event["decoded_type"] = "combogift"
                
                # 解码 payload
                if "payload" in app_msg and app_msg["payload"]:
                    try:
                        decoded_payload = base64.b64decode(app_msg["payload"]).decode('utf-8')
                        gift_payload = json.loads(decoded_payload)
                        
                        event["sec_gift_id"] = gift_payload.get("reward_product_id", "")
                        event["combo_product_count"] = gift_payload.get("combo_product_count", 0)
                        event["content"] = gift_payload.get("content", "")
                    except Exception as e:
                        Logger.get_logger("wx_data_decoder").error(f"解码连击礼物 payload 失败: {str(e)}")
                
            elif event["msg_sub_type"] == 20006:  # 点赞
                event["decoded_type"] = "like"
                
            elif event["msg_sub_type"] == 20031:  # 等级提升
                event["decoded_type"] = "levelup"
                
                # 解码 payload
                if "payload" in app_msg and app_msg["payload"]:
                    try:
                        decoded_payload = base64.b64decode(app_msg["payload"]).decode('utf-8')
                        level_payload = json.loads(decoded_payload)
                        
                        event["from_level"] = level_payload.get("from_level", 0)
                        event["to_level"] = level_payload.get("to_level", 0)
                    except Exception as e:
                        Logger.get_logger("wx_data_decoder").error(f"解码等级提升 payload 失败: {str(e)}")
                
            else:
                event["decoded_type"] = "unknown"
                event["original_data"] = app_msg
            
            return event
            
        except Exception as e:
            Logger.get_logger("wx_data_decoder").error(f"提取应用消息事件失败: {str(e)}")
            return None
    
    @staticmethod
    def get_open_id_from_msg_id(msg_id):
        """
        从消息ID中提取OpenID - 与 wxlivespy 项目逻辑一致
        
        @param msg_id: 消息ID
        @return: 提取的OpenID
        """
        # 示例: "msg_id": "finderlive_usermsg_comment_1F4EF489-B2CE-4B26-9002-3C7421EF8E78_o9hHn5apfwHL-RYrxochETS7NyDM"
        # 返回: 'o9hHn5apfwHL-RYrxochETS7NyDM'
        try:
            idx = msg_id.find("_o9h")
            if idx >= 0:
                return msg_id[idx+1:]
            return None
        except:
            return None
    
    @staticmethod
    def get_sec_open_id_from_msg_id(msg_id):
        """
        从消息ID中提取SecOpenID - 与 wxlivespy 项目逻辑一致
        
        @param msg_id: 消息ID
        @return: 提取的SecOpenID
        """
        # 示例: "finderlive_appmsg_finderlive_commcommentnotify_d5addee68407c6d78fe2cc115ef3bcbf_2042584726460027863_1698657150_b2afac411cfad2d6f5fe69e1c2ec3901"
        # 返回: 'b2afac411cfad2d6f5fe69e1c2ec3901'
        try:
            parts = msg_id.split("_")
            if parts and len(parts) >= 1:
                return parts[-1]
            return None
        except:
            return None 